import { DrawInteractor } from "./drawInteractor";
import PolyLineNodeGraph from "../shape/polyline";
import { Point } from "@/shape/dependencies";
import { getScale } from "@/graphviewState";
export class PolyLineDrawInteractor extends DrawInteractor {
  points: { x: number; y: number }[] = [];
  movePoint: { x: number; y: number } = { x: 0, y: 0 };
  drawing: boolean = false;
  ctx: CanvasRenderingContext2D | null;
  borderColor = "rgb(64,158,255)";
  mouseDownTime = 0;
  mouseUpTime = 0;
  interval = 200;
  constructor(target: HTMLCanvasElement) {
    super(target);
    this.ctx = this.target.getContext("2d");
  }
  handleMouseDown(e: MouseEvent) {
    // 防止双击时执行两次
    const time = Date.now();
    const interval = time - this.mouseDownTime;
    if (interval < this.interval) {
      return;
    }
    this.mouseDownTime = time;
    this.drawing = true;
  }
  handleMouseUp(e: MouseEvent) {
    // 防止双击时执行两次
    const time = Date.now();
    const interval = time - this.mouseUpTime;
    if (interval < this.interval) {
      return;
    }
    this.mouseUpTime = time;
    const point = { x: e.offsetX, y: e.offsetY };
    this.points.push(point);
  }
  handleDoubleClick() {
    this.drawing = false;
    this.drawEnd();
  }
  handleMouseMove(e: MouseEvent) {
    if (this.drawing) {
      this.movePoint.x = e.offsetX;
      this.movePoint.y = e.offsetY;
      this.reDraw();
    }
  }
  reDraw() {
    if (this.ctx) {
      this.emit("redraw");
      this.draw();
    }
  }
  draw() {
    if (!this.ctx) {
      return;
    }
    if (this.points.length === 0) {
      return;
    }
    const startPoint = this.points[0];
    this.ctx.restore();
    this.ctx.strokeStyle = this.borderColor;
    this.ctx.beginPath();
    this.ctx.moveTo(startPoint.x, startPoint.y);
    for (let i = 1; i < this.points.length; i++) {
      const point = this.points[i];
      this.ctx.lineTo(point.x, point.y);
    }
    this.ctx.lineTo(this.movePoint.x, this.movePoint.y);
    this.ctx.stroke();
  }
  drawEnd() {
    if (this.points.length <= 1) {
      // 只是在原点点击了一下,不会进行绘制
      return;
    }
    // 去除缩放对鼠标获取点坐标的影响
    const scale = getScale();
    const polyLine = new PolyLineNodeGraph();
    polyLine.points = this.points.map((point) => {
      return new Point(point.x / scale, point.y / scale);
    });
    polyLine.saveOriginPoints();
    this.emit("drawend", polyLine);
  }
}
